<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ServiceCustomField.class.php, $Author:  $ */



/** Service for working with custom fields
 *
 * @package module.account
 * @version $Id: PhpFox_ServiceCustomField.class.php 46 2007-12-14 23:12:21Z phpfoxsv $
 *
 */
class PhpFox_Mod_Account_ServiceCustomField extends BaseService
{
    /** Deleting any custom field
     *
     * @param integer $iFieldId
     * @return boolean
     */
    function deleteField($iFieldId)
    {
        $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

        $iFieldId = intval($iFieldId);
        $sSql = 'DELETE FROM '.App::getT('custom_field_option').' WHERE custom_field_id = '.$iFieldId;
        $oCustomFieldItem->oDb->query($sSql);
        $sSql = 'DELETE FROM '.App::getT('custom_field2user').' WHERE custom_field_id = '.$iFieldId;
        $oCustomFieldItem->oDb->query($sSql);
        $sSql = 'DELETE FROM '.App::getT('custom_field2text').' WHERE custom_field_id = '.$iFieldId;
        $oCustomFieldItem->oDb->query($sSql);
        $sSql = 'DELETE FROM '.App::getT('custom_field').' WHERE custom_field_id = '.$iFieldId;
        $oCustomFieldItem->oDb->query($sSql);
        return true;
    }

    /** Get fields list with default option title
     *
     * @param array $aCond
     * @param integer $iPage
     * @param integer $iPageSize
     * @param string $sSort
     * @return array
     */
    function getFields($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '')
    {
        $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

        $aMap = $oCustomFieldItem->aFields;
        $sCond = $oCustomFieldItem->_parseCond($aCond, $aMap);
        $sSql = 'SELECT COUNT(*) '.
                ' FROM `'.App::getT('custom_field').'` AS cf '.
                ' LEFT JOIN `'.App::getT('custom_field_option').'` AS cfo ON cf.custom_field_id = cfo.custom_field_id AND cfo.custom_option_is_default = 1 '.
                ' WHERE '.$sCond;
        $iCnt = $oCustomFieldItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $iOffset = $oCustomFieldItem->_getOffset($iPage, $iPageSize, $iCnt);
            $sSql = 'SELECT cf.custom_field_id AS custom_field_id, cf.custom_field_name AS custom_field_name, cf.custom_field_pos AS custom_field_pos, cf.custom_field_type, cf.panel, cf.signup, cfo.custom_option_name AS custom_field_default_option '.
                    ' FROM `'.App::getT('custom_field').'` AS cf '.
                    ' LEFT JOIN `'.App::getT('custom_field_option').'` AS cfo ON cf.custom_field_id = cfo.custom_field_id AND cfo.custom_option_is_default = 1 '.
                    ' WHERE '.$sCond.
                    ($sSort ? (' ORDER BY '.$sSort) : '').
                    ($iPageSize ? (' LIMIT '.$iOffset.','.$iPageSize) : '');
            $aRows = $oCustomFieldItem->oDb->getRows($sSql, true);
        }
        return array($aRows, $iCnt);
    }

    /** Get all profile fields for current user
     *
     * @return array
     */
    function getFieldsForProfileText($iUserId = 0)
    {
	    if (!$iUserId)
	    {
    	    $oSecurityService = App::getModuleService('Account', 'Security');
            /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
            $oCurrentUser = $oSecurityService->getCurrentUser();
            $iUserId = $oCurrentUser->aData['id'];
	    }

		$sSql = "SELECT cf.custom_field_id, cf.custom_field_name, ct.textarea FROM
			". App::getT('custom_field') ." AS cf
			LEFT JOIN ". App::getT('custom_field2text') ." AS ct ON (ct.user_id = '". $iUserId ."' AND cf.custom_field_id = ct.custom_field_id)
			WHERE cf.custom_field_type = '1'
			ORDER BY cf.custom_field_pos
			";
		$aFields = $this->oDatabase->getRows($sSql);

		return $aFields;

    }

    function getTextFields($iUserId, $sType)
    {
    	static $aTextAreas;

    	if ( !$aTextAreas )
    	{
        	$sSql = "SELECT ct.textarea, cf.custom_field_name, cf.panel FROM
    			". App::getT('custom_field2text') ." AS ct,
    			". App::getT('custom_field') ." AS cf
    			WHERE user_id = '". $iUserId ."' AND cf.custom_field_id = ct.custom_field_id
    			ORDER BY cf.custom_field_pos
    			";
    		$aTextAreas = $this->oDatabase->getRows($sSql);
    	}

    	$sPanel = array();

    	$iType = ($sType == 'left' ? '0' : '1');

    	foreach($aTextAreas as $sTexts)
    	{
    		if ( $sTexts['panel'] == $iType )
    		{
    			$sPanel[] = $sTexts;
    		}
    	}

		return $sPanel;
    }

    /** Get all profile fields for current user
     *
     * @return array
     */
    function getFieldsForProfile($iUserId = 0)
    { 
	    if (!$iUserId)
	    {
    	    $oSecurityService = App::getModuleService('Account', 'Security');
            /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
            $oCurrentUser = $oSecurityService->getCurrentUser();
            $iUserId = $oCurrentUser->aData['id'];
	    }
	    $sSql = 'SELECT cf.custom_field_id, cf.custom_field_name, cf.custom_field_pos, cf2u.custom_option_id, cfo.custom_option_name '.
	           ' FROM `'.App::getT('custom_field').'` cf '.
	           ' LEFT JOIN `'.App::getT('custom_field2user').'` AS cf2u ON cf2u.custom_field_id = cf.custom_field_id AND cf2u.user_id = '.$iUserId.' '.
 	           ' LEFT JOIN `'.App::getT('custom_field_option').'` AS cfo USING(custom_option_id) WHERE cf.custom_field_type = "0"'.
 	           // ' GROUP BY custom_option_name '.
	           ' ORDER BY custom_field_pos';
	    $aFields = $this->oDatabase->getRows($sSql);

	    foreach ($aFields as $iKey => $aField)
	    {
	        $sSql = 'SELECT custom_option_name AS name, custom_option_id AS id, custom_option_is_default AS is_default '.
	               ' FROM `'.App::getT('custom_field_option').'` AS cfo '.
	               ' WHERE custom_field_id = '.$aField['custom_field_id'].' '.
	               ' ORDER BY custom_option_is_default DESC, custom_option_name';
	        $aOptions = App::cacheData("custom_options_". $aField['custom_field_id'] ."", $sSql);
	        $aOptionsHash = array();
	        $aDefault = array();
	        foreach ($aOptions as $aOption)
	        {
	        	if ( $aOption['is_default'] )
	        	{
	        		$aDefault['is_default'] = $aOption['is_default'];
	        	}
	            $aOptionsHash[$aOption['id']] = $aOption['name'];
	        }
	        $aFields[$iKey]['options'] = $aOptionsHash;
	        $aFields[$iKey]['selected'] = (isset($aFields[$iKey]['custom_option_id']) ? $aFields[$iKey]['custom_option_id'] : (isset($aDefault['is_default']) ? $aDefault['is_default'] : ''));
	    }
	    return $aFields;
    }

	/** Get fields list with options
     *
     * @return array
     */
    function getFieldsList()
    {
        $sSql = 'SELECT cf.custom_field_id, cf.custom_field_name, cf.custom_field_pos '.
	           ' FROM `'.App::getT('custom_field').'` cf WHERE cf.custom_field_type = "0"'.
	           ' ORDER BY custom_field_pos';
	    $aFields = App::cacheData("custom_fields", $sSql);
	    foreach ($aFields as $iKey => $aField)
	    {
	        $sSql = 'SELECT custom_option_name AS name, custom_option_id AS id, custom_option_is_default AS is_default '.
	               ' FROM `'.App::getT('custom_field_option').'` AS cfo '.
	               ' WHERE custom_field_id = '.$aField['custom_field_id'].' '.
	               ' ORDER BY custom_option_is_default DESC, custom_option_name';
	        $aOptions = App::cacheData("custom_options_". $aField['custom_field_id'] ."", $sSql);
	        $aOptionsHash = array();
	        foreach ($aOptions as $aOption)
	        {
	            $aOptionsHash[$aOption['id']] = $aOption['name'];
	        }
	        $aFields[$iKey]['options'] = $aOptionsHash;
	    }
	    return $aFields;
    }

    /** Deleting any option and reassign user choice to default option
     *
     * @param integer $iOptionId
     * @return boolean
     */
    function deleteOption($iOptionId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

        $iOptionId = intval($iOptionId);
        if (!$oCustomFieldOptionItem->load($iOptionId))
        {
            return false;
        }
        if ($oCustomFieldOptionItem->aData['custom_option_is_default'])
        {
            return false;
        }
        $iFieldId = $oCustomFieldOptionItem->aData['custom_field_id'];
        $aDefaultOption = $this->getDefaultOption($iFieldId);
        $aUpdateArray = array
        (
            'custom_option_id' => $aDefaultOption['custom_field_id'],
        );
        $oCustomFieldOptionItem->oDb->update(App::getT('custom_field2user'), $aUpdateArray, 'custom_field_id = '.$iFieldId.' AND custom_option_id = '.$iOptionId);
        $oCustomFieldOptionItem->delete($iOptionId);
        return true;
    }

    function getBrowseTextNames()
    {
    	$sQuery = "SELECT custom_field_id AS id, custom_field_name AS name FROM ". App::getT('custom_field') ."
    			WHERE `custom_field_type` = '1'";
    	return App::cacheData("custom_browe_textareas", $sQuery);
    }

    function getSignupFields()
    {
    	$oReq = &App::getRequest();
    	$text_option = $oReq->getArray('text_option');
    	$drop_option = $oReq->getArray('field_option');

        $sSql = 'SELECT cf.custom_field_id, cf.custom_field_name, cf.custom_field_type, cf.custom_field_pos '.
	           ' FROM `'.App::getT('custom_field').'` cf WHERE cf.signup = "1"'.
	           ' ORDER BY custom_field_pos';
	    $aFields = $this->oDatabase->getRows($sSql);
	    foreach ($aFields as $iKey => $aField)
	    {
	    	$aFields[$iKey]['post_value'] = (isset($text_option[$aFields[$iKey]['custom_field_id']]) ? $text_option[$aFields[$iKey]['custom_field_id']] : '');
	    	$aFields[$iKey]['post_select'] = (isset($drop_option[$aFields[$iKey]['custom_field_id']]) ? $drop_option[$aFields[$iKey]['custom_field_id']] : '');

	        $sSql = 'SELECT custom_option_name AS name, custom_option_id AS id, custom_option_is_default AS is_default '.
	               ' FROM `'.App::getT('custom_field_option').'` AS cfo '.
	               ' WHERE custom_field_id = '.$aField['custom_field_id'].' '.
	               ' ORDER BY custom_option_is_default DESC, custom_option_name';
	        $aOptions = $this->oDatabase->getRows($sSql);
	        $aOptionsHash = array();
	        foreach ($aOptions as $aOption)
	        {
	            $aOptionsHash[$aOption['id']] = $aOption['name'];
	        }
	        $aFields[$iKey]['options'] = $aOptionsHash;
	    }
    	return $aFields;
    }

    /** Get deafault option row for field
     *
     * @param integer $iFieldId
     * @return array
     */
    function getDefaultOption($iFieldId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

	    $sSql = 'SELECT custom_option_name, custom_option_id '.
	           ' FROM '.App::getT('custom_field_option').' '.
	           ' WHERE custom_field_id = '.$iFieldId.' '.
	           '   AND custom_option_is_default = 1';
	    return $oCustomFieldOptionItem->oDb->getRow($sSql);
    }

    /** Add new field and set default option for it
     *
     * @param integer $iPos
     * @param string $sTitle
     * @param string $sOption
     * @return integer field id
     */
    function addNewField($iPos, $sTitle, $sOption, $sType, $sSignup, $sPanel)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */
	    $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

	    $iPos = intval($iPos);
	    if (!$iPos || !$sTitle || !$sOption)
	    {
	        return array(false, false);
	    }
	    $oCustomFieldItem->aData['custom_field_name'] = $sTitle;
	    $oCustomFieldItem->aData['custom_field_pos']  = $iPos;
	    $oCustomFieldItem->aData['custom_field_type']  = $sType;
	    $oCustomFieldItem->aData['panel']  = $sPanel;
	    $oCustomFieldItem->aData['signup']  = $sSignup;
	    $iFieldId = $oCustomFieldItem->insert();

	    if ( $sType == "" )
	    {
	    	$oCustomFieldOptionItem->aData['custom_field_id']          = $iFieldId;
	    	$oCustomFieldOptionItem->aData['custom_option_name']       = $sOption;
	    	$oCustomFieldOptionItem->aData['custom_option_is_default'] = 1;
	    	$iOptionId = $oCustomFieldOptionItem->insert();
	    }

	    return array($iFieldId, (isset($iOptionId) ? $iOptionId : ''));
    }

    /** Update data for custom field
     *
     * @param integer $iFieldId
     * @param string $sTitle
     * @param integer $iPos
     * @param string $sDefOption
     * @return boolean
     */
    function updateField($iFieldId, $sTitle, $iPos, $sDefOption, $iPanel, $iSignup)
    {
	    $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

	    $iFieldId = intval($iFieldId);
	    $iPos = intval($iPos);
	    $oCustomFieldItem->load($iFieldId);
	    $oCustomFieldItem->aData['custom_field_name'] = $sTitle;
	    $oCustomFieldItem->aData['custom_field_pos']  = $iPos;
	    $oCustomFieldItem->aData['panel']  = $iPanel;
	    $oCustomFieldItem->aData['signup']  = $iSignup;
	    $oCustomFieldItem->update(array('custom_field_name', 'custom_field_pos', 'panel', 'signup'));
	    return true;
    }

    function updateProfileSettings($aFields, $aFieldsText = "", $iUser = "")
    {
        $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */
	    $oSecurityService = App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

		if ( !$iUser )
		{
	        $oCurrentUser = $oSecurityService->getCurrentUser();
	        $iUser = $oCurrentUser->aData['id'];
		}

		if ( count($aFields) != 0 )
		{
        	foreach ($aFields as $iFieldId => $iSelectedOptionId)
        	{
        		$doCheck = $oCustomFieldItem->oDb->getRow("SELECT COUNT(*) AS count FROM ". App::getT('custom_field2user') ." WHERE
        			user_id = '". $iUser ."' AND custom_field_id = '". $iFieldId ."'");
        		if ( !$doCheck['count'] )
				{
					$oCustomFieldItem->oDb->query("INSERT INTO ". App::getT('custom_field2user') ." SET
						user_id = '". $iUser ."',
						custom_field_id = '". $iFieldId ."',
						custom_option_id = '". $iSelectedOptionId ."'
						");
				}
				else
				{
        	    	$aArr = array
        	    	(
        	    	    'custom_option_id' => $iSelectedOptionId,
        	    	);
        	    	$oCustomFieldItem->oDb->update(App::getT('custom_field2user'), $aArr, 'custom_field_id = '.$iFieldId.' AND user_id = '.$iUser);
				}
        	}
        }

		if ( count($aFieldsText) != 0 )
		{
        	App::loadClass('Text');
        	$oTxt = &new Text();

	        foreach ($aFieldsText as $iFieldTextId => $sText)
	        {
	        	$sText = $oTxt->preParseText($sText);

	        	$doCheckText = $oCustomFieldItem->oDb->getRow("SELECT COUNT(*) AS count FROM ". App::getT('custom_field2text') ." WHERE
		        		user_id = '". $iUser ."' AND custom_field_id = '". $iFieldTextId ."'");
	   	     	if ( !$doCheckText['count'] )
				{
					$aQueryText = array
					(
						'user_id' => ''. $iUser .'',
						'custom_field_id' => ''. $iFieldTextId .'',
						'textarea' => ''. ($sText) .'',
					);
					$oCustomFieldItem->oDb->insert(App::getT('custom_field2text'), $aQueryText);
				}
				else
				{
	        		$aTextArr = array
	        		(
	        			'textarea' => $sText,
	        		);
					$this->oDatabase->update(App::getT('custom_field2text'), $aTextArr, 'custom_field_id = '.$iFieldTextId.' AND user_id = '.$iUser);
				}
			}
		}

		return true;
    }

    /** Set option in any field as default
     *
     * @param integer $iFieldId
     * @param integer $iOptionId
     * @return boolean
     */
    function setDefault($iFieldId, $iOptionId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

	    $aUpdate = array
	    (
	        'custom_option_is_default' => 0,
	    );
	    $oCustomFieldOptionItem->oDb->update(App::getT('custom_field_option'), $aUpdate, 'custom_field_id = '.$iFieldId);
	    $oCustomFieldOptionItem->load($iOptionId);
	    $oCustomFieldOptionItem->aData['custom_option_is_default'] = 1;
	    $oCustomFieldOptionItem->update(array('custom_option_is_default'));
	    return true;
    }

    /** Set default options for all users in system
     *
     * @param integer $iFieldId
     * @param integer $iOptionId
     * @return boolean
     */
    function setUserOption($iFieldId, $iOptionId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

        $sSql = 'INSERT INTO '.App::getT('custom_field2user').' '.
               ' SELECT u.id AS user_id, '.$iFieldId.' AS custom_field_id, '.$iOptionId.' AS custom_option_id '.
               ' FROM '.App::getT('user').' AS u';
        return $oCustomFieldOptionItem->oDb->query($sSql);
    }

    /** Set default oiptions for user wityh specified id
     *
     * @param integer $iUserId
     * @return boolean
     */
    function newUserSetDefault($iUserId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

        $sSql = 'INSERT INTO '. App::getT('custom_field2user') .' '.
               ' SELECT '.$iUserId.' AS user_id, cf.custom_field_id AS custom_field_id, cfo.custom_option_id AS custom_option_id '.
               ' FROM '.App::getT('custom_field').' AS cf '.
			   ' LEFT JOIN '.App::getT('custom_field_option').' AS cfo ON cfo.custom_field_id = cf.custom_field_id AND cfo.custom_option_is_default = 1';
		$oCustomFieldOptionItem->oDb->query($sSql);
	    return true;
    }

    function deleteUserChoices($iUserId)
    {
        $oCustomFieldOptionItem = &$this->_oModule->getItem('CustomFieldOption');
	    /* @var $oCustomFieldOptionItem PhpFox_Mod_Account_ItemCustomFieldOption */

	    $iUserId = intval($iUserId);
	    return $oCustomFieldOptionItem->oDb->query('DELETE FROM '.App::getT('custom_field2user').' WHERE user_id = '.$iUserId);
    }

    function getMaxFieldPos()
    {
        $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

	    $sSql = 'SELECT MAX(custom_field_pos) '.
	           ' FROM `'.App::getT('custom_field').'`';
	    return $oCustomFieldItem->oDb->getField($sSql);
    }

    function updateFieldPosition($iFrom)
    {
        $oCustomFieldItem = &$this->_oModule->getItem('CustomField');
	    /* @var $oCustomFieldItem PhpFox_Mod_Account_ItemCustomField */

	    $iFrom = intval($iFrom);
	    $sSql = 'SELECT custom_field_id, custom_field_pos '.
	           ' FROM `'.App::getT('custom_field').'` '.
	           ' WHERE custom_field_pos >= '.$iFrom.' '.
	           ' ORDER BY custom_field_pos, custom_field_id DESC';
	    $aFields = $oCustomFieldItem->oDb->getRows($sSql);
	    $sSql = 'SELECT MAX(custom_field_pos) '.
	           ' FROM `'.App::getT('custom_field').'` '.
	           ' WHERE custom_field_pos < '.$iFrom;
	    $iMaxIdBefore = $oCustomFieldItem->oDb->getField($sSql);
	    $iCounter = $iMaxIdBefore;
	    foreach ($aFields as $aField)
	    {
	        $iCounter++;
	        $oCustomFieldItem->load($aField['custom_field_id']);
	        $oCustomFieldItem->aData['custom_field_pos'] = $iCounter;
	        $oCustomFieldItem->update(array('custom_field_pos'));
	    }
	    return true;
    }
}
?>